package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Autowired
private ClazzMapper clazzMapper;
    @Override
    public PageResult<Student> pageQuery(StudentQueryParam param) {
        Page<Student> page = new Page<>(param.getPage(), param.getPageSize());
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<Student>()
                .like(!StringUtils.isEmpty(param.getName()), Student::getName, param.getName())
                .eq(!StringUtils.isEmpty(param.getDegree()), Student::getDegree, param.getDegree())
                .eq(!StringUtils.isEmpty(param.getClazzId()), Student::getClazzId, param.getClazzId())
                .orderByDesc(Student::getId);

        //分页
        this.page(page, queryWrapper);
        List<Student> records = page.getRecords();
        records.forEach(student -> {
            Integer clazzId = student.getClazzId();
            Clazz clazz = clazzMapper.selectById(clazzId);
            if (clazz != null) {
                student.setClazzName(clazz.getName());
            }

        });

        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    @Override
    public void update(Student student) {
       student.setUpdateTime(LocalDateTime.now());
        updateById(student);
    }

    @Override
    public void violation(Integer id, Integer score) {
        Student student = getById(id);
        student.setViolationScore((short) (student.getViolationScore() + score));
        student.setViolationCount((short) (student.getViolationCount() + 1));
        updateById(student);
    }
}
